<?php

    class WorktimeController extends Zend_Controller_Action {
        
        protected $model, $model_user;
        protected $form;
        protected $user;
        protected $worktimeUserSessKey;
        
        protected static $CALENDAR_SIX_USERS = array("Spalte 1","Spalte 2","Spalte 3","Spalte 4","Spalte 5","Spalte 6"), $CALENDAR_ONE_USER = 1;
        protected static $SESSION_NAMESPACE = "WorktimeController";
        protected static $USER_PREFIX = "USER_";
        
        public function init() 
        {
            $this->_helper->acl->allow('admin')->allow('user', array('index'));
            $model_user = new Model_User();
	        $this->model = new Model_Worktime();
            /*$_redirector = $this->_helper->getHelper('Redirector');
            if(!$model_user->isLoggedIn())
                return $_redirector->gotoUrl($this->getRequest()->getBaseUrl().'/auth/login');*/
            $this->user = Zend_Auth::getInstance()->getIdentity();
	        $this->form = new Application_Form_Worktime();
	        $contextSwitch = $this->_helper->getHelper('contextSwitch');
            $contextSwitch->addActionContext('index', 'json')->initContext();
            $this->view->modus = "Arbeitszeiten";
            $this->view->helperArray = array();
            $this->view->alternatives = array();
            $namespace = new Zend_Session_Namespace();
            $this->worktimeUserSessKey = $this::$USER_PREFIX.$this->user['idperson'];
            if(!isset($_SESSION[$this::$SESSION_NAMESPACE]))
                $_SESSION[$this::$SESSION_NAMESPACE] = array();
            if(!isset($_SESSION[$this::$SESSION_NAMESPACE][$this->worktimeUserSessKey]))
                $_SESSION[$this::$SESSION_NAMESPACE][$this->worktimeUserSessKey] = array();
            if(!isset($_SESSION[$this::$SESSION_NAMESPACE][$this->worktimeUserSessKey]['CALENDAR']))
                $_SESSION[$this::$SESSION_NAMESPACE][$this->worktimeUserSessKey]['CALENDAR'] = array();
            $this->view->calendarStatusArray = $_SESSION[$this::$SESSION_NAMESPACE][$this->worktimeUserSessKey]['CALENDAR'];
            if(!is_array($this->view->calendarStatusArray))
                $this->view->calendarStatusArray = array();
            $this->view->bIsAdmin = $this->isAdmin();
            $this->view->userId_ = strval($this->user['idperson']);
        }

        /**
         * This class manages all HTTP requests send to worktimes.
         */

        public function indexAction() 
        {
            $r = $this->model->listWorkers();
            $this->view->aWorkers = $r;
	        if($this->_request->isXmlHttpRequest())
	        {
                // any ajax calendar events ? handle them
                $this->handleAjaxEvents();
                // send worktime events to the JQuery calendar
                $this->sendEvents();                
	        }             
        }

        public function newAction() 
        {
	        $form = $this->form;
	        $model = $this->model;
	        $r = $model->listWorkers();
	        $request = $this->getRequest();
            
	        //$this->showCalendar();

	        if(count($r) > 0) 
	        {
	            $dropdown = $form->getElement("Mitarbeiter");
	            foreach($r as $sub_array) 
	            {
		            $dropdown->addMultiOptions(array($sub_array['id']=>$sub_array['forename']." ".$sub_array['surname']));
	            }
                
                //$this->from->aWorkersSelect = $b;

                //$expireDate = $form->getElement("expire_date");
                //$expireDate->setValue("2012-02-02 12:12");
                
	        }

	        if($request->isPost()) 
	        {
	            $a = $request->getPost();

                if(isset($a['modus']))
                    $this->view->modus = ($a['modus']=="wt") ? "Arbeitszeiten":"Verfügbarkeiten";

                if(!isset($a['once_serie'])) {
                /*$once_serie = $form->getElement("once_serie");
                $once_serie->setValue('e');*/
                    $a['once_serie'] = 'e';                    
                
                }
                
                if(!isset($a['x_days'])) 
                $a['x_days'] = '7';
                /*if(!$a['x_days'] || $a['x_days']<0)
                    $a['x_days'] = '7';*/
                    
                if(isset($a['Mitarbeiter'])) {
                    if(strval($a['Mitarbeiter'])==0)
                        $a['Mitarbeiter']=$r[0]['id'];
                }

                if(!isset($a['Mitarbeiter']) && count($r)>0) 
                    $a['Mitarbeiter']=$r[0]['id'];

                if(!isset($a['expire_date'])) {
                    $a['expire_date'] = substr($a['date_to'],0,10);
                }
                
                $this->view->helperArray = $a;
                $form->populate($a);
                
	            if($form->isValid($a))
	            {   
                    if(isset($a['submit'])) {
                        $bSerie = ($a['once_serie']=='s' || $a['once_serie']=='x') ? true:false;
                        /* check for some date and time errors 
                           for serie events and none */
                        $errors = ($a['once_serie']=='e') ? $this->validateDates($a):$this->validateDates($a,true);
                        
                        $this->view->errors = $errors;
                        if(0==(strlen($errors) && 1)) {
		                    $model->addWorkTime($a,$bSerie);
		                    return $this->_helper->redirector('index');
                        }
                    }
                }
	            else {}
	        }

	

	        $this->view->form = $form;
        }

        public function updateAction() 
        {
            $request = $this->getRequest();
            $id = (int)$request->getParam('id');
            $form = new Application_Form_WorktimeUpdate();
            $r = $this->model->listWorkers();
            $dropdown = $form->getElement("Mitarbeiter");
            $model = $this->model;
            $serieId = $this->model->getWorkTimeSerieId($id);
            $__modus = "";
            $this->view->serieId = $serieId;
            
            // if id zero or undefined redirect to index URL
            if(!$id) {
                return $this->_helper->redirector('index');
            }
            
            
	        if ($request->isPost()) 
	        {
		        $c = $form->getValues();
		        $c['id'] = $id;
		        $dropdown->setValue($c['Mitarbeiter']);
		        foreach($r as $sub_array) 
                {
			        $dropdown->addMultiOptions(array($sub_array['id']=>$sub_array['forename']." ".$sub_array['surname']));
		        }
                
                $f0 = $request->getPost();
                $this->view->helperArray = $f0;

                if(!isset($f0['x_days'])) 
                    $f0['x_days'] = '7';
                if(!$f0['x_days'] || $f0['x_days'] < 0)
                    $f0['x_days'] = '7';
                if(isset($f0['modus'])) {
                    $this->view->modus = ($f0['modus']=="wt") ? "Arbeitszeiten":"Verfügbarkeiten";
                    $__modus = $f0['modus'];
                }
                    
		        if ($form->isValid($f0)) 
		        {
                    $cc = $request->getPost();
                    $cc['id_update'] = $id;
                    $errors = $this->validateDates($cc);
                                                                             
                    $this->view->errors = $errors;

                    if(0==(strlen($errors) && 1)) 
                    {
                        $model->updateWorkTime($id,$request->getPost());
			            return $this->_helper->redirector('index');
                    }
		        }
	        }
	        else
	        {
		        $c = $this->model->find($id);
		        foreach($r as $sub_array) 
		        {
			        $dropdown->addMultiOptions(array($sub_array['id']=>$sub_array['forename']." ".$sub_array['surname']));
		        }
		        $dropdown->setValue($c['idperson']);
		        $c['date_from']=$this->get_worker_dt_from_mysql_dt($c['date_from']);
		        $c['date_to']=$this->get_worker_dt_from_mysql_dt($c['date_to']);

                if(strcmp($c['worktime_type'],"worktime"))
                {
                    $c['modus'] = "av";
                    $this->view->modus = "Verfügbarkeiten";
                }
                else
                {
                    $c['modus'] = "wt";
                    $this->view->modus = "Arbeitszeiten";                
                }
                $__modus = $c['modus'];
                $this->view->helperArray = $c;
		        $form->populate($c);
	        }
            
            if(strcmp($__modus,"wt")==0)
                $this->view->alternatives = $model->getAlternatesForWorktime($id);

	        $this->view->form = $form;
            $this->view->id = $id;
        }
        
        public function bookalternativeAction() 
        {
            $request = $this->getRequest();
            $id = (int)$request->getParam('id');
            $model = $this->model;
            
	        if ($request->isPost()) 
	        {
		        $c = $request->getPost();
                $c['id'] = $id;
                $model->bookAlternative($c);
            }
	        return $this->_helper->redirector('index');         
        }
        
        public function availabilitytoworktimeAction() 
        {
            $request = $this->getRequest();
            $id = (int)$request->getParam('id');
            $form = new Application_Form_WorktimeAvailabilitytoworktime();
            $r = array();
            $dropdown = $form->getElement("Mitarbeiter");
            $model = $this->model;
            $serieId = $this->model->getWorkTimeSerieId($id);

            $this->view->serieId = $serieId;

	        if ($request->isPost()) 
	        {
		        $c = $form->getValues();
		        $c['id'] = $id;
                
                $f0 = $request->getPost();
                $f0['modus'] = "av";
                $this->view->helperArray = $f0;
                
                $r = $model->getWorkerById($f0['Mitarbeiter']);
		        
                $dropdown->addMultiOptions(array($r['id']=>$r['forename']." ".$r['surname']));
                $dropdown->setValue($c['Mitarbeiter']);                
                /*print "<pre>";
                print_r($f0);
                print "</pre>";*/

                if(isset($f0['modus']))
                    $this->view->modus = "Verfügbarkeiten";                    
                    
		        if ($form->isValid($f0)) 
		        {
                    $cc = $request->getPost();
                    $cc['id_update'] = $id;
                    $errors = $this->validateDates($cc);
                                                                             
                    $this->view->errors = $errors;

                    if(0==(strlen($errors) && 1)) 
                    {
                        $e = $model->generateWorktimeFromAvailability($id,$f0);
                        if($e['success']==true)
                            return $this->_helper->redirector('index');
                        else
                            $this->view->errors = $e['errors'];
                        
                    }
		        }
	        }
	        else
	        {
		        $c = $this->model->find($id);
                $r = $model->getWorkerById($c['idperson']);
                
                $dropdown->addMultiOptions(array($r['id']=>$r['forename']." ".$r['surname']));
		        $dropdown->setValue($c['idperson']);
		        
                $c['date_from']=$this->get_worker_dt_from_mysql_dt($c['date_from']);
		        $c['date_to']=$this->get_worker_dt_from_mysql_dt($c['date_to']);
                $c['modus'] = "av";
                //$c['description'] = "";
                $this->view->modus = "Verfügbarkeiten";
                $this->view->helperArray = $c;
		        $form->populate($c);
	        }

	        $this->view->form = $form;
            $this->view->id = $id;
        }        

        public function deleteAction() 
        {
	        $request = $this->getRequest();
            $c = $request->getParams();            
                        
            //$id = (int)$request->getParam('id');
            // delete one event
            if(isset($c['id']))
                $this->model->deleteWorktime($c['id']);
            // delete whole serie
            else if(isset($c['ids']))            
                $this->model->deleteWorktimeSerie($c['ids']);
	        return $this->_helper->redirector('index');
        }
        
        protected function setToCalendarSession($key,$value) 
        {
            return $_SESSION[$this::$SESSION_NAMESPACE][$this->worktimeUserSessKey]['CALENDAR'][$key] = $value;
        }        
        
        protected function getFromCalendarSession($key) 
        {
            return $_SESSION[$this::$SESSION_NAMESPACE][$this->worktimeUserSessKey]['CALENDAR'][$key];
        }
	
	    // get date and time values out of mysql datetime string
        public function get_datetime_from_mysql($str,$flag)
        {
	        $str0="";
	        if(strlen($str)) {
	            switch($flag) {
		        case "Y":
		            $str0=substr($str,0,4);
		            break;
		        case "m":
	         	    $str0=substr($str,5,2);
		            break;
		        case "d":
		            $str0=substr($str,8,2);
		            break;
		        case "H":
		            $str0=substr($str,11,2);
		            break;
		        case "i":
		            $str0=substr($str,14,2);
		            break;
		        case "s":
		            $str0=substr($str,17,2);
		            break;
		        default:
		            break;
	            }
	        }
	        return $str0;
        }
	
        // convert mysql datetime format to => dd.MM.yyyy HH:mm
        public function get_worker_dt_from_mysql_dt($dt)
        {
	        $str_dt="";
	        if(strlen($dt)>0) {
	            $str_dt=sprintf("%02s.%02s.%04s %02s:%02s",
			            $this->get_datetime_from_mysql($dt,'d'),
			            $this->get_datetime_from_mysql($dt,'m'),
			            $this->get_datetime_from_mysql($dt,'Y'),
			            $this->get_datetime_from_mysql($dt,'H'),
			            $this->get_datetime_from_mysql($dt,'i'));
            }
	        return $str_dt;
        }

        public function showCalendar() 
        {
        }
        
        /**
         * @deprecated dont use this function anymore
         */
        /*public function listAction() 
        {
	        //$form = $this->form;
	        $model = $this->model;
	        $r = $model->getWorktime();
	        $last_id=-1;
	        foreach($r as $sub_array) 
	        {
                if($sub_array['idperson']!=$last_id) 
                    print "<br>&nbsp;&nbsp;&nbsp;&nbsp;<b>".$sub_array['forename']." ".$sub_array['surname']."</b><br>&nbsp;&nbsp;&nbsp;&nbsp;ID : ".$sub_array['idperson']."<br>";
	                print '&nbsp;&nbsp;&nbsp;&nbsp;<b>von :</b> '.$sub_array['date_from'].'&nbsp;&nbsp;<b>bis :</b> '.$sub_array['date_to'].'&nbsp;&nbsp;&nbsp;&nbsp;<a href="/worktime/update/id/'.$sub_array['id'].'">&Auml;ndern</a>&nbsp;&nbsp;<a href="/worktime/delete/id/'.$sub_array['id'].'">Entfernen</a><br>';
	                $last_id=$sub_array['idperson'];
	        }
        }*/

        protected function sendEvents() {

            $_users="";
            $numUsers = (int)strval($this->_getParam("numUsers"));
            $workerFlag = (int)strval($this->_getParam("idWorker"));
            $worktimeType = $this->_getParam("modus");

            /* decide how manys users show be shown at the same time 
               by catching the value of calendar event select box */
            switch($numUsers) {
                case 2:
                    // 6 slots per day
                    $_users = $this::$CALENDAR_SIX_USERS;
                    break;
                case 0:
                case 1:
                default:
                    // 1 slot per day
                    $_users = $this::$CALENDAR_ONE_USER;
                    break;
            }
                

            $this->_helper->contextSwitch('json');

            $startDate = $this->_getParam("startDate");
            $stopDate = $this->_getParam("endDate");
            
            $this->setToCalendarSession('startDate',$startDate);
            $this->setToCalendarSession('stopDate',$stopDate);
            $this->setToCalendarSession('modus',$worktimeType);
            $this->setToCalendarSession('idWorker',$workerFlag);
            $this->setToCalendarSession('numUsers',$numUsers);
            

            $worktimes = $this->model->getWorktimes($startDate,$stopDate,$worktimeType,!$workerFlag ? 'all':$workerFlag);
            //$worktimesAV = $this->model->getWorktimes($startDate,$stopDate,'av',!$workerFlag ? 'a':$workerFlag);

            $r = array();
            $fb = array();
            $uid = 0;
            $day = 0; $last_day = 0;
            
            foreach($worktimes as $wt) {
                if($uid==6)
                    $uid=0;
                
                // requesting person data
                $pid = $wt['idperson'];
                $aPerson = $this->model->getWorkerById($pid);
                $sPerson = $aPerson['forename']." ".
                           $aPerson['surname'];
                $day = (int)strval($this->get_datetime_from_mysql($wt['date_from'],'d'));
                if($day!=$last_day)
                    $uid&=0;

	            $r[]=array(
                   'id' => $wt['id'],
                   'start' => $wt['date_from'],
                   'end' => $wt['date_to'],
                   'title' => '<b>'.$sPerson.'<br>'.($wt['idworktime_series']>0 ? "S ".$wt['idworktime_series']:"").'<br>'.'</b>'.$wt['description'],
                   'category' => '',
                   'userId' => $uid,
                   'personId' => $pid//$wt['idperson']
                );      
                $uid++;
                $last_day=$day;
            }
            
            /*$uid = 0;
            $day = 0; $last_day = 0;            
            
            if($worktimeType=='wt') {
                foreach($worktimesAV as $wt) {
                    if($uid==6)
                        $uid=0;

                    $day = (int)strval($this->get_datetime_from_mysql($wt['date_from'],'d'));
                    if($day!=$last_day)
                        $uid&=0;
                    
                    $fb[]=array(
                       'start' => $wt['date_from'],
                       'end' => $wt['date_to'],
                       'free' => 'true',
                       'userId' => $uid//$wt['idperson']
                    );                
                    $uid++;
                    $last_day=$day;
                }
            }*/      
            
            //"start": new Date(year, month, day+0, 00), "end": new Date(year, month, day+3, 00, 00), "free": false, userId: [0,1,2,3]
            
            $r0=array(
               'options'=>array(
                  /*'timeslotsPerHour'=>4,
                  'timeslotHeight'=>20,
                  'use24Hour'=>"true",*/
                  'users'=>$_users
                  /*'allowCalEventOverlap'=>"true",
                  'overlapEventsSeparate'=>"false",
                  'defaultFreeBusy'=>array("free"=>"true")*/
               ),
              'events'=>$r,
              'freebusys'=>$fb
            );

            $this->_helper->json->sendJson($r0);            
        }

        /**
         * @deprecated no need using this anymore
         */
        function showWeekEvents($date1,$date2) {
            $this->view->events = $this->model->getWorkTimes($date1,$date2);
        }

        protected function handleAjaxEvents() {
        
            $this->_helper->contextSwitch('json');

            $eventType = $this->_getParam("event");
            $startDate = $this->_getParam("date_from");
            $stopDate = $this->_getParam("date_to");
            $eventID = (int)strval($this->_getParam("id"));
            $modus = $this->_getParam("modus");

            if(!!strlen($eventType) && strlen($startDate) && strlen($stopDate) && $eventID) {
                switch($eventType) {
                     case "eventDrop": 
                     case "eventResize":
                     {
                         $a = array(
                            'id'=>$eventID,
                            'date_from'=>$startDate,
                            'date_to'=>$stopDate,
                            'modus'=>$modus,
                            'Mitarbeiter'=>$this->model->getWorkerIdByWorktimeId($eventID),
                            'id_update'=>$eventID
                         );
                         
                         $errors = "";
                         $n = array("success"=>true,
                                    "message"=>"");
                                    
                         if($modus=="wt") {
                            $errors = $this->validateDates($a);
                         }
                         if(!strlen($errors)) {
                            $this->model->updateWorkTimeOnEvent($a);
                            $n['message'] = "Update der Zeit erfolgreich.";
                         } else {
                            $n['success'] = false;
                            $msg = strip_tags($errors);
                            $n['message'] = $msg;
                         }
                         
                         $this->_helper->json->sendJson($n);
                     }  
                     default:
                     break;
                }
            }
        }

        protected function get_unixtimestamp($dt) {
            $ut = 0; // secs
            if(strlen($dt)>0) {
                $Y = strval(substr($dt,6,4));
                $m = strval(substr($dt,3,2));
                $d = strval(substr($dt,0,2));
                $H = strval(substr($dt,11,2));
                $i = strval(substr($dt,14,2));
                $s = 0;
                
                /* arguments : hour minute second month day year */
                $ut = mktime($H,$i,$s,$m,$d,$Y);
            }
            return $ut;
        }
        
        protected function validateDates($a,$bSerie=false) {
            $str_errors = "";
            if(is_array($a)) {
                if(count($a)) {
                    $date_from = $a['date_from'];
                    $date_to = $a['date_to'];
                    if(isset($a['expire_date']))
                        $a['expire_date'].=" 23:59";

                    /*[date_from] => 07.01.2013 13:30
                      [date_to] => 07.01.2013 14:00
                      [once_serie] => e
                      [Mitarbeiter] => 3
                      [expire_date] => 07.01.2013 14:00*/

                    /* get seconds difference  
                       between start and end date */
                    
                    $d_to = $this->get_unixtimestamp($date_to);
                    $diff = -$this->get_unixtimestamp($date_from) + $d_to;

                    if($diff<0) 
                        $str_errors = sprintf("<br>Die Zeit für das Ende der Arbeit/Verfügbarkeit muss nach der Anfangszeit liegen und nicht davor.");
                    
                    // series ?
                    if($bSerie) {

                        $expire_date = $a['expire_date'];

                        /* check for series difference to end date */ 

                        $diff = -$d_to + $this->get_unixtimestamp($expire_date);

                        if($diff<0) {
                            $str_errors = sprintf("%s<br>Die Zeit für das Ende einer Serie muss nach dem Ende der Arbeitszeit/Verfügbarkeit liegen und nicht davor.",$str_errors);
                        }
                        
                        if(isset($a['x_days'])) {
                            $x_days = (int)strval($a['x_days']);
                            if($x_days<=0) {
                                $str_errors = sprintf("%s<br>Tagesschritte dürfen nicht kleiner oder gleich 0 sein.",$str_errors);
                            }
                            
                        }

                        /*if(strcmp(substr($date_from,0,10),substr($date_to,0,10))!=0) {
                            $str_errors = sprintf("%s<br>Bei einer Serie muss das Datum der End- und Anfangszeit gleich sein, nur der Zeitanteil (Stunde:Minute) darf sich ändern.",$str_errors);
                        }*/
                    }
                    
                    /* check availability for worktime and look
                       after collision with other worktime entries */
                    if($a['modus']=="wt") {
                                          
                        $r0 = $a;
                        $r0['modus'] = "av";
                        $r0['modus_for'] = "wt";
                        $r = $this->model->checkTimeForExistence($r0,$bSerie);
                        $bAvail = false;
                        
                        if(!$r['success']) {
                            
                            if(!$bSerie)
                                $str_errors = sprintf("%s<br>Für die Zeit <b>%s</b> - <b>%s</b> und die ausgewählte Person existieren keine Verfügbarkeiten, bitte tragen Sie zuerst welche ein.",
                                                      $str_errors,$a['date_from'],$a['date_to']);
                            else if($bSerie)
                                $str_errors = sprintf("%s<br>Für die Serienzeit <b>%s</b> - <b>%s</b> bis <b>%s</b> und die ausgewählte Person existieren ab dem <b>%s</b> keine oder keine gültige Verfügbarkeiten, bitte tragen Sie zuerst welche ein.",
                                                      $str_errors,$a['date_from'],$a['date_to'],$a['expire_date'],$this->get_worker_dt_from_mysql_dt($r['date_from']));
                        } else
                            $bAvail = true;
                            
                        if($bAvail) {
                            /* lets do a final check to determine if we have got a collision 
                               with already booked times for the person */
                            $r0['modus'] = "wt";
                            $r = $this->model->checkTimeForExistence($r0,$bSerie,true);
                            
                            # now we need to check for collision success for worktimes
                            if($r['success']) {
                            
                                if(!$bSerie)
                                    $str_errors = sprintf("%s<br>Für die Zeit <b>%s</b> - <b>%s</b> und die ausgewählte Person besteht eine Kollision bzw. die Person ist für das Datum bereits gebucht.",
                                                          $str_errors,$a['date_from'],$a['date_to']);
                                else if($bSerie)
                                    $str_errors = sprintf("%s<br>Für die Serienzeit <b>%s</b> - <b>%s</b> bis <b>%s</b> und die ausgewählte Person besteht ab dem <b>%s</b> eine Kollision bzw. die Person ist für das Datum bereits gebucht.",
                                                          $str_errors,$a['date_from'],$a['date_to'],$a['expire_date'],$this->get_worker_dt_from_mysql_dt($r['date_from']));
                            }                            
                        }

                    } else if($a['modus']=="av") {
                                          
                        $r0 = $a;
                        $r = $this->model->checkTimeForExistence($r0,$bSerie,true);
                        
                        # now we need to check for collision success for availabilities
                        if($r['success']) {
                        
                            if(!$bSerie)
                                $str_errors = sprintf("%s<br>Für die Zeit <b>%s</b> - <b>%s</b> und die ausgewählte Person besteht eine Kollision mit bereits eingetragenen Verfügbarkeiten.",
                                                      $str_errors,$a['date_from'],$a['date_to']);
                            else if($bSerie)
                                $str_errors = sprintf("%s<br>Für die Serienzeit <b>%s</b> - <b>%s</b> bis <b>%s</b> und die ausgewählte Person besteht ab dem <b>%s</b> eine Kollision mit bereits eingetragenen Verfügbarkeiten.",
                                                      $str_errors,$a['date_from'],$a['date_to'],$a['expire_date'],$this->get_worker_dt_from_mysql_dt($r['date_from']));
                        }                 
                    }
                }
            }
            return $str_errors;
        }
        
        protected function computeTimeCollision($t1_begin,$t1_end,$t2_begin,$t2_end) {
        
            /* compute collision of 2 unix timestamp intervals */
            $bCollision = false;
            
            /* fast comparision */
            
            if($t1_begin >= $t2_end || $t1_end <= $t2_begin)
                return false;
            
            /* no success ? go through a loop by swapping 
               time operands and do relational tests */
               
            for($i=0;$i<2;$i+=1) {
                if($t1_begin == $t2_begin || $t1_end == $t2_end)
                    $bCollision |= true;
                else if(($t1_begin < $t2_begin && $t1_end > $t2_end) || ($t1_begin > $t2_begin && $t1_end < $t2_end))
                    $bCollision |= true;
                else if($t1_begin > $t2_begin && $t1_begin < $t2_end)
                    $bCollision |= true;
                else if($t1_begin < $t2_begin && $t1_end > $t2_begin)
                    $bCollision |= true;
                if($bCollision)
                    break;
                else {
                    $tmp_begin = $t1_begin; $tmp_end = $t1_end;
                    $t1_begin = $t2_begin; $t1_end = $t2_end;
                    $t2_begin = $tmp_begin; $t2_end = $tmp_end;                    
                }
            }
                        
            return $bCollision;            
        }
        
        protected function doesEventCollid($a,$event_type) {
            $bCollision = false;
            if(is_array($a)) {
                if(count($a)) {
                    $idp = $a['Mitarbeiter'];
                    $events = array();
                    switch($event_type) {
                        case "avav":
                        break;
                        case "wtwt":
                        break;
                        case "wtav":
                        break;
                    }
                }
            }
            return $bCollision;
        }
        
        protected function isAdmin() {
            $bIsAdmin = false;
            if(is_array($this->user)) {
                if(count($this->user)) {
                    $bIsAdmin = ((isset($this->user['is_admin']) ?  $this->user['is_admin']:'N')!='Y') ? false:true;
                }
            }
            return $bIsAdmin;
        }
        
        protected function redirectIfNotAdmin() {
            if(!$this->isAdmin())
                return $this->_helper->redirector('index');        
        }
        
        

    }



?>
